<template>
  <div class="pic-cut">
    <h2>使用三方库实现图片自由裁剪</h2>
    <h2>
      可以得到裁剪后的图片所有数据，如有需要可以搭配UI框架实现上传等系列效果
    </h2>
    <ImgCutter v-on:cutDown="cutDown" />
    <h3>在下面展示裁剪后的图片</h3>
    <hr />
    <div class="img-box" v-if="backFileList.length">
      <div class="img-item" v-for="(item, index) in backFileList" :key="index">
        <img :src="item.url" />
        <CloseCircleOutlined class="close-icon" @click="deleteImg(index)" />
        <p>{{ item?.name }}</p>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "PicCut",
};
</script>

<script setup>
import ImgCutter from "vue-img-cutter";
import { CloseCircleOutlined } from "@ant-design/icons-vue";
import { ref } from "vue";
import { message } from "ant-design-vue";

const fileList = ref([]);

let file = ref(null);

const backFileList = ref([]);

const cutDown = (file) => {
  file.value = file.file;
  fileList.value.push(file.file);
  const reader = new FileReader();
  reader.onload = function (readerEvent) {
    const base64Data = readerEvent.target.result;
    backFileList.value.push({
      url: base64Data,
      name: file.file.name,
    });
  };
  reader.readAsDataURL(file.value);
};

const deleteImg = (index) => {
  fileList.value.splice(index, 1);
  backFileList.value.splice(index, 1);
  message.success("删除成功");
};
</script>

<style lang="scss" scoped>
.pic-cut {
  h2 {
    text-align: center;
  }
  h3 {
    margin: 20px 0;
  }
  .img-box {
    margin-top: 20px;
    display: flex;
    flex-wrap: wrap;
    align-items: center;

    .img-item {
      margin-right: 10px;

      img {
        width: 110px;
        height: 110px;
        object-fit: cover;
      }

      .close-icon {
        color: #fff;
        position: relative;
        top: -48px;
        left: -7px;
        background: #00a4ff;
        border-radius: 50%;
      }

      p {
        margin-top: 5px;
        text-align: center;
        width: 100%;
        color: #00a4ff;
        width: 100px;
        overflow: hidden;
        word-wrap: break-word;
        padding: 5px 0;
      }
    }
  }
}
</style>